package com.ap.autobase.repository.impl;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.NonUniqueObjectException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Criterion;
import org.springframework.beans.factory.annotation.Autowired;

import com.ap.autobase.repository.GenericDao;

public class GenericDaoImpl<T, Key extends Serializable> implements
		GenericDao<T, Key> {
	@Autowired
	private SessionFactory sessionFactory;

	protected Session getSession() {
		return sessionFactory.getCurrentSession();
	}

	@SuppressWarnings("unchecked")
	protected Class<T> getGenericEntityClass() {
		ParameterizedType parameterizedType = (ParameterizedType) getClass()
				.getGenericSuperclass();
		return (Class<T>) parameterizedType.getActualTypeArguments()[0];
	}

	@SuppressWarnings("unchecked")
	public T getById(Key id) {

		return (T) getSession().get(getGenericEntityClass(), id);
	}

	@SuppressWarnings("unchecked")
	public List<T> getAll() {

		Criteria cr = getSession().createCriteria(getGenericEntityClass());
		return (List<T>) cr.list();
	}

	@SuppressWarnings("unchecked")
	public List<T> getByParameter(Criterion parameter) {
		Criteria cr = getSession().createCriteria(getGenericEntityClass());
		cr.add(parameter);
		return (List<T>) cr.list();
	}

	@SuppressWarnings("unchecked")
	public void deleteById(Key id) {

		T persistentObject = (T) getSession().load(getGenericEntityClass(), id);
		try {
			getSession().delete(persistentObject);
		} catch (NonUniqueObjectException e) {
			T instance = (T) getSession().merge(persistentObject);
			getSession().delete(instance);
		}

	}

	@SuppressWarnings("unchecked")
	public void delete(T persistentObject) {
		try {
			getSession().delete(persistentObject);
		} catch (NonUniqueObjectException e) {
			// in a case of detached object
			T instance = (T) getSession().merge(persistentObject);
			getSession().delete(instance);
		}
	}

	@SuppressWarnings("unchecked")
	public Key save(T obj) {
		return (Key) getSession().save(obj);
	}

	public void update(T obj) {
		getSession().update(obj);
	}

}
